package com.sinog.biz.schedule;

import com.sinog.biz.mapper.havexml.HnInterfaceOppositeMapper;
import com.sinog.biz.mapper.havexml.PrisonerXjxxMapper;
import com.sinog.biz.mapper.havexml.VerificationMapper;
import com.sinog.biz.service.api.XmlMinitoringService;
import com.sinog.biz.service.business.impl.PrisonerMainServiceImpl;
import com.sinog.biz.service.business.impl.VerificationServiceImpl;
import com.sinog.biz.util.FtpUtil;
import com.sinog.core.domain.PrisonerHc;
import com.sinog.core.domain.PrisonerMain;
import com.sinog.core.domain.PrisonerXjxx;
import com.sinog.core.domain.xml.HnInterfaceOpposite;
import com.sinog.core.model.PrisonerXixxVo;
import com.sinog.core.model.UserDTO;
import com.sinog.core.util.StrUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @desc 定时任务：定时从ftp服务器接收目录拉取全部文件，并且循环文件列表，调取解析接口，然后删除接收目录的文件
 * @author lzq
 * @date 2021-09-20 00:02
 */
@Slf4j
@Component
@Configuration
@ConditionalOnProperty(name = "gkzx.azbj.zip.open", havingValue = "true")
public class HnSchedule {

    @Value("${gkzx.azbj.zip.pull.ip}")
    private String ip;
    /**
     * 前置机ftp port
     */
    @Value("${gkzx.azbj.zip.pull.port}")
    private int port;
    /**
     * 前置机ftp username
     */
    @Value("${gkzx.azbj.zip.pull.username}")
    private String username;
    /**
     * 前置机ftp password
     */
    @Value("${gkzx.azbj.zip.pull.password}")
    private String password;
    /**
     * 前置机ftp timeout
     */
    @Value("${gkzx.azbj.zip.pull.timeout}")
    private int tomeout;
    @Value("${gkzx.azbj.zip.pull.ftppath}")
    private String ftppath;
    @Autowired
    private XmlMinitoringService xmlMinitoringService;
    /**
     * 执行补偿逻辑
     */
    @Autowired
    private HnInterfaceOppositeMapper hnInterfaceOppositeMapper;
    @Autowired
    private VerificationServiceImpl verificationService;
    @Autowired
    private PrisonerMainServiceImpl prisonerMainService;
    @Autowired
    private VerificationMapper verificationMapper;
    @Autowired
    private PrisonerXjxxMapper prisonerXjxxMapper;

    /**
     * 湖南个性化对接:定时扫描ftp目录,下载zip文件进行解析
     */
   @Scheduled(cron = "${gkzx.azbj.zip.pull.cron}")
    public void getFilesFromFtp() {
        log.info("开始从ftp服务器{}:{}读取zip包",ip,port);
        Map<String, String> hzMap = new HashMap<>(16);
        FTPClient ftp = FtpUtil.getFtpClient(ip,port,username,password);
        //设置ftp连接超时时间5秒
        ftp.setConnectTimeout(tomeout);
        try {
            FTPFile[] ftpFiles = ftp.listFiles(ftppath);
            for (FTPFile ftpFile : ftpFiles) {
                String name = ftpFile.getName();
                log.info("开始处理文件{}",ftppath + name);
                if (name.endsWith(Constants.ImageEndType.FILE_END_ZIP)) {
                    Result monitoring = xmlMinitoringService.monitoring(name);
                    if(null != monitoring) {
                        if(!Objects.isNull(monitoring.getData())) {
                            hzMap = (( HashMap<String, String>) monitoring.getData());
                            hzMap.put("MESSAGE",monitoring.getMessage());
                        }
                        xmlMinitoringService.makeFile(hzMap);
                    }
                    assert monitoring != null;
                    log.info("开始删除ftp文件{}",ftppath + name);
                    boolean b = ftp.deleteFile(ftppath + name);
                    while(!b){
                        b = ftp.deleteFile(ftppath + name);
                    }
                    log.info("删除ftp文件{}成功",ftppath + name);
                }
            }
        } catch(IOException | DocumentException | SAXException e) {
            log.error("Error monitoring:{}",e.getMessage());
        }
        log.info("从ftp服务器读取zip包完成");
    }

    /**
     * 湖南个性化对接:定时补偿,若看守所发送外省,由外省核查成功后,返回0702B与0702F压缩包
     * 定时任务:每日凌晨执行1次
     */
    @Scheduled(cron = "${gkzx.azbj.zip.pull.syncCron}")
    public void hnScheduledCompensate() {
        /**
         * 执行步骤
         * 1. 查询hn_interface_opposite表中所有的pri_num
         * 2. 根据查询的pri_num查找数据库
         * 3. 查询湖南看守所是否正常发送回执包,如果没有则进行发送
         */
        List<HnInterfaceOpposite> hnInterfaceOpposites = hnInterfaceOppositeMapper.selectAllPriNum();
        for(HnInterfaceOpposite hnInterfaceOpposite : hnInterfaceOpposites) {
            String priNum = hnInterfaceOpposite.getPriNum();
            String hcType = hnInterfaceOpposite.getHcType();
            String xjType = hnInterfaceOpposite.getXjType();
            String hzHcZip = hnInterfaceOpposite.getHzHcZip();
            String hzXjzip = hnInterfaceOpposite.getHzXjZip();
            // 根据priNum查找服刑人员信息,如果state=3或state=4则司法所执行过完成核查,如果hzHcZip为0,则需发送回执zip
            PrisonerMain prisonerMain = prisonerMainService.selectPmById(priNum);
            String state = prisonerMain.getState();
            if(StrUtil.containsEquals(state,Constants.NumberStr.NUM_STR_THREE,Constants.NumberStr.NUM_STR_FOUR)
                    && !Constants.NumberStr.NUM_STR_ONE.equals(hzHcZip)) {
                PrisonerHc prisonerHc = verificationMapper.selectHcByPriNum(priNum);
                if(Constants.NumberStr.NUM_STR_ZERO.equals(hcType)) {
                    UserDTO userDTO = new UserDTO();
                    userDTO.setDepartName(prisonerHc.getConmectuserName());
                    userDTO.setTelphone(prisonerHc.getConmectuserPhone());
                    verificationService.signFor(priNum,Constants.NumberStr.NUM_STR_ONE,userDTO);
                }
                // 发送补偿的0702B
                verificationService.hcResult(prisonerMain,prisonerHc,Constants.NumberStr.NUM_STR_THREE.equals(state) ? Boolean.TRUE:Boolean.FALSE);
            }
            // 查找是否满足衔接成功条件,如果hcXjZip为0,则需发送回执zip
            String stateXj = prisonerMain.getStateXj();
            if(StrUtil.containsEquals(stateXj,Constants.NumberStr.NUM_STR_ONE,Constants.NumberStr.NUM_STR_THREE)
                    && !Constants.NumberStr.NUM_STR_ONE.equals(hzXjzip)) {
                PrisonerXjxx xjxxByPriNum = prisonerXjxxMapper.getXjxxByPriNum(priNum);
                PrisonerXixxVo prisonerXjxx = new PrisonerXixxVo();
                prisonerXjxx.setPriNum(priNum);
                prisonerXjxx.setRemark(xjxxByPriNum.getRemark());
                prisonerXjxx.setStatexj(stateXj);
                PrisonerHc prisonerHc = verificationMapper.selectHcByPriNum(priNum);
                UserDTO userDTO = new UserDTO();
                userDTO.setDepartName(prisonerHc.getConmectuserName());
                userDTO.setTelphone(prisonerHc.getConmectuserPhone());
                if(Constants.NumberStr.NUM_STR_ZERO.equals(xjType)) {
                    verificationService.signFor(priNum,Constants.NumberStr.NUM_STR_THREE,userDTO);
                }
                // 发送补偿的0702F
                prisonerMainService.xjhz(userDTO,prisonerXjxx);
            }
        }
    }
}